#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import datetime

from dateutil.parser import parse
from six.moves import builtins

import flask_excel as excel
from flask import Flask, render_template, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, current_user

from config import config
from reverse_proxied import ReverseProxied

app = Flask(__name__)

"""
这边只用sql alchemy 进行管理员的控制, 就两种管理员
administrator and viewer
"""

config_name = os.environ.get("crm_env", "default")
app.config.from_object(config[config_name])
config[config_name].init_app(app)

db = SQLAlchemy(app)
app.wsgi_app = ReverseProxied(app.wsgi_app)

login_manager = LoginManager(app)
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
login_manager.login_message = (u"请登陆系统")
login_manager.login_message_category = "info"

login_manager.refresh_view = "auth.logout"
login_manager.needs_refresh_message = (u"账号密码过期，请从新登陆")
login_manager.needs_refresh_message_category = "info"


#excel
excel.init_excel(app)

"""
blueprint
you can register a <blueprint> by run:
 -- nnamage blueprint <blueprint>
under app folder

"""
from app.auth import views as auth_view
app.register_blueprint(auth_view.bp, url_prefix='/auth')

from app.users import views as users_view
app.register_blueprint(users_view.bp, url_prefix='/users')

from app.loans import views as loans_view
app.register_blueprint(loans_view.bp, url_prefix='/loans')

from app.admin import views as admin_view
app.register_blueprint(admin_view.bp, url_prefix='/admin')

from app.download import views as download_view
app.register_blueprint(download_view.bp, url_prefix='/download')

app.jinja_env.line_statement_prefix = '#'
app.jinja_env.globals.update(builtins.__dict__)

"""
app exception
"""

@app.route('/')
def index():
    if current_user.is_active:
        return redirect(url_for("users.preloan_index"))
    else:
        return redirect(url_for('auth.login'))


@app.template_filter('date')
def date(s):
    if isinstance(s, datetime.datetime):
        return s.strftime("%Y-%m-%d")
    if isinstance(s, str):
        try:
            s = parse(s)
            return s.strftime("%Y-%m-%d")
        except:
            return s


@app.template_filter('truncate')
def truncate(s):
    if len(s) > 20:
        return s[:20] + "..."
    else:
        return s


@app.errorhandler(404)
def page_not_found(e):
    return render_template('base/404.html'), 404


@app.errorhandler(500)
def internal_server_error(e):
    return render_template('base/500.html'), 500

